<?php

// +----------------------------------------------------------------------
// | 第三方支付
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2022 http://www.yicmf.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 微尘 <yicmf@qq.com>
// +----------------------------------------------------------------------

namespace app\event\pay;

use app\common\event\Base;
use app\event\ucenter\User as UserEvent;
use app\model\ucenter\UserCash as UserCashModel;
use app\ucenter\event\UserAuth as UserAuthEvent;
use think\facade\Db;
use app\model\ucenter\User as UserModel;
use app\pay\model\Pay as PayModel;
use think\Exception;
use yicmf\tools\FlowSn;

class UserCash extends Base
{


    public function apply($param, $user)
    {
        try {
            if (cache('cash_' . $user['id'])) {
                throw new Exception('操作频繁，请稍后');
            }
            cache('cash_' . $user['id'], 1, 10);
            $minMoney = 10;
            if ($param['cash_money'] < $minMoney) {
                throw new Exception('账户余额必须大于' . $minMoney . '才能提现');
            }
            if ($param['cash_money'] > 10000) {
                throw new Exception('提现超额');
            }
            $userMoney = $user['money'];
            if ($userMoney < $param['cash_money']) {
                throw new Exception('账户余额不足');
            }
            $fee = $param['cash_money'] * 0.09 + 2;

            if (!$user['realName']) {
                throw new Exception('您还没有进行实名认证');
            }
            if (empty($user['alipay_no']) && empty($param['alipay_no'])) {
                throw new Exception('您还没有绑定支付宝');
            }
            if (!empty($param['alipay_no'])) {
                $user['alipay_no'] = $param['alipay_no'];
            }

            if (UserCashModel::where('user_id', $user['id'])->whereTime('create_time', 'today')->find()) {
                throw new Exception('每天限制提现一次');
            }

            $data = [
                'user_id' => $user['id'],
                'bank_no' => $user['alipay_no'],
                'cash_money' => $param['cash_money'],
                'before_money' => $userMoney,
                'after_money' => $userMoney - $param['cash_money'],
                'status' => 0,
                'bank_type' => 1,
                'cash_charge' => $fee,
                'real_cash' => $param['cash_money'] - $fee,
                'real_name' => $user['realName']
            ];
            Db::startTrans();
            $message = '提交成功';
            if ($param['cash_money'] <= 100) {
                $data['status'] = 1;
                $data['audit_time'] = time_format();
                $data['billId'] = date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
                //支付宝返款调用
                $transferRes = alipay_transfer($data['billId'],round($data['real_cash'],2),$data['bank_no'],$data['real_name']);
                if ($transferRes['code'] !== 0) {
                    throw new Exception('提现失败！'.$transferRes['msg']);
                }
                $data['orderId'] = $transferRes['order_id'];

                $message = '秒到提现成功';
            }
            $user['cash_num'] = $user['cash_num'] + 1;
            $user->save();
            $info = UserCashModel::create($data);
            if (!$info) {
                throw new Exception('提现记录异常');
            }
            UserEvent::money(-$param['cash_money'], $user['id'], '余额提现', 1, $user['id']);
            Db::commit();

            $data['data'] = $message;
            $data['code'] = 0;
        } catch (Exception $exception) {
            Db::rollback();
            $data['message'] = $exception->getMessage();
            $data['code'] = 1;
        }
        return $data;
    }


    public function check($param, $admin)
    {
        try {

            $cash = UserCashModel::where('id', $param['id'])->where('status', 0)->find();
            if (!$cash) {
                throw new Exception('记录不存在');
            }
            $cash['status'] = $param['status'];
            $cash['reject'] = $param['reject'];
            $cash['admin_id'] = $admin['id'];
            if ($cash['cash_charge'] != $param['cash_charge']) {
                $cash['cash_charge'] = $param['cash_charge'];
                $cash['real_cash'] = $cash['cash_money'] - $cash['cash_charge'];
            }
            $user = UserModel::where('id', $cash['user_id'])->find();
            if (!$user) {
                throw new Exception('会员信息异常');
            }
            Db::startTrans();
            if ($param['status'] == 1) {
                // 通过
                $cash['audit_time'] = time_format();
                $cash['orderId'] = FlowSn::build(8);
                $cash['billId'] = date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
                //支付宝返款调用
                $transferRes = alipay_transfer($cash['billId'], round($cash['real_cash'], 2), $cash['bank_no'], $cash['real_name']);
                if ($transferRes['code'] !== 0) {
                    throw new Exception('提现失败！'.$transferRes['msg']);
                }
                $cash['orderId'] = $transferRes['order_id'];
                $user['cash_num'] = $user['cash_num'] + 1;
                $user->save();

            }else{
                //失败退回
                UserEvent::money($cash['cash_money'], $user['id'], '提现驳回【'.$param['reject'].'】', 2, $user['id']);
            }
            if (!$cash->save()) {
                throw new Exception('提现记录异常');
            }

            Db::commit();

            $data['message'] = '操作成功';
            $data['code'] = 0;
        } catch (Exception $exception) {
            Db::rollback();
            $data['message'] = $exception->getMessage();
            $data['code'] = 1;
        }
        return $data;
    }

}
